package com.cn.wanxi.springsecurity.service.impl;

import com.cn.wanxi.springsecurity.domain.Permission;
import com.cn.wanxi.springsecurity.domain.User;
import com.cn.wanxi.springsecurity.mapper.PermissionMapper;
import com.cn.wanxi.springsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description 负责用户认证的实现类
 * @Author JiJiang
 * @Date 2022/9/26 16:41
 * @Version 1.0
 */

@Service
@CrossOrigin
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    UserMapper userMapper;


    @Autowired
    PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        System.out.println(username);

        //region static
//        //1. 创建一个UserDetils对象
//        // 2. 创建一组GrantedAuthority代表权限
//        User userEntity = new User();
//        // demo/111111
////        userEntity.setName("demo");
//        userEntity.setUsername("test");
//        // 这里一定要使用加密后的密码
//        userEntity.setPassword("123456789");
//
//        Permission permission = new Permission();
//        permission.setValue("cx:create_user");
//
//        Permission permission2 = new Permission();
//        permission2.setValue("cx:update_user");
//
//        Set<Permission> set = new HashSet<>();
//        set.add(permission);
//        set.add(permission2);
//
//        userEntity.setAuthorities(set);
//
//
//
//
//        return userEntity;

        //endregion

        //region dynamic

        //1.根据输入的用户名查询实际的用户信息  --->这里可能为null;
        User user = userMapper.selectByUsername(username);

        if (user == null) {
            return user;
        }
        //2.获取该用户的id
        long userId = user.getId();

        //3.根据id获取该用户的所有权限
        Set<Permission> permissionSet = permissionMapper.selectByUserId((int) userId);

        //4.给user设置对应权限
        user.setAuthorities(permissionSet);

        //endregion

        return user;

    }
}
